package com.zimin.cloud.wiki.biz.impl;

import com.zimin.cloud.mine.pojo.wiki.business.CategoryBO;
import com.zimin.cloud.mine.pojo.wiki.view.CategoryVO;
import com.zimin.cloud.wiki.biz.ICategoryBiz;
import com.zimin.cloud.wiki.service.impl.CategoryServiceImpl;
import com.zimin.common.annotation.Biz;
import com.zimin.common.enums.Number;
import com.zimin.common.utils.ObjectUtils;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * <p>
 * 分类 业务对象
 * </p>
 *
 * @author zimin
 * @since 2021-10-27 21:02
 */
@Biz
public class CategoryBizImpl extends CategoryServiceImpl implements ICategoryBiz {

    @Override
    public List<CategoryVO> allTree(CategoryBO categoryBO) {
        List<CategoryVO> allCategoryVO = list(categoryBO);
        if (ObjectUtils.isEmpty(allCategoryVO)) {
            return List.of();
        }
        return tree(allCategoryVO, Number.ZERO.getStrNum());
    }

    /**
     * <p>获取分类树</p>
     *
     * @param categoryVOList 原List
     * @param parent         上级父ID
     * @return java.util.List<com.zimin.cloud.mine.pojo.wiki.view.CategoryVO>
     * @since 2021-11-24 16:55:59
     */
    private List<CategoryVO> tree(List<CategoryVO> categoryVOList, String parent) {
        Map<String, List<CategoryVO>> childrenMap = categoryVOList.stream()
                .collect(Collectors.groupingBy(CategoryVO::getParent));
        List<CategoryVO> children = childrenMap.get(parent);
        children.forEach(categoryVO -> {
            String parentNodeId = categoryVO.getId();
            List<CategoryVO> categoryVOList1 = childrenMap.get(parentNodeId);
            if (ObjectUtils.isNotEmpty(categoryVOList1)) {
                List<CategoryVO> tree = tree(categoryVOList, parentNodeId);
                categoryVO.setChildren(tree);
            }
        });
        return children;
    }


}
